#include "main.h"
#include "ev1527_decoder.h"
#include "string.h"

#define RF433_SYNC_FLAG   			0x80
#define RF433_EDGE_FLAG   			0x10

void ev1527_decoder_init(ev1527_decoder_t *decoder, ev1527_data_callback_t cb)
{
    decoder->status = 0;
    decoder->data = 0;
    decoder->bit_count = 0;
		decoder->data_count = 0;
		memset(decoder->data_buff, 0, sizeof(decoder->data_buff));
		decoder->callback = cb;
}

void ev1527_decoder_on_update(ev1527_decoder_t *decoder)
{
    if (decoder->status & RF433_SYNC_FLAG) 
		{
        decoder->status &= ~RF433_EDGE_FLAG;
        if ((decoder->status & 0x0F) < 14) 
				{
            decoder->status++;
        }
    }
}

void ev1527_decoder_on_capture(ev1527_decoder_t *decoder, uint8_t level, uint16_t duration) 
{
    if (level) 
		{
        // Rising edge
        if (decoder->status & RF433_EDGE_FLAG) 
				{
            if ((duration > (RF433_SYNC_L - RF433_FILTER)) && (duration < (RF433_SYNC_L + RF433_FILTER))) 
						{
                decoder->data = 0;
                decoder->status |= RF433_SYNC_FLAG;
                decoder->bit_count = 0;
            }
        }
        decoder->status &= ~RF433_EDGE_FLAG;
    } 
		else 
		{
        // Falling edge
        if (decoder->status & RF433_SYNC_FLAG)
				{
            decoder->data <<= 1;
            if ((duration > (RF433_BIT1_L - RF433_FILTER)) && (duration < (RF433_BIT1_L + RF433_FILTER))) 
						{
                decoder->data |= 0;
            } 
						else if ((duration > (RF433_BIT0_L - RF433_FILTER)) && (duration < (RF433_BIT0_L + RF433_FILTER))) 
						{
                decoder->data |= 1;
            } 
						else 
						{
                decoder->status &= ~RF433_SYNC_FLAG;
                decoder->bit_count = 0;
                return;
            }
            decoder->bit_count++;
            if (decoder->bit_count >= 24) 
						{
                decoder->status &= ~RF433_SYNC_FLAG;
                decoder->bit_count = 0;
								decoder->data_buff[decoder->data_count++] = decoder->data;
                if (decoder->data_count > 2)
								{
										if(decoder->data_buff[1] == decoder->data_buff[2])
										{
											decoder->callback(decoder->data_buff[2]);
										}
										decoder->status = 0;
										decoder->data = 0;
										decoder->bit_count = 0;
										decoder->data_count = 0;
										memset(decoder->data_buff, 0, sizeof(decoder->data_buff));
								}

            }
        }
        decoder->status |= RF433_EDGE_FLAG;
    }
}
